const koa = require('koa');
const bodyParser = require('koa-bodyparser');

const app = new koa();
app.use(bodyParser());

function sleep(ts) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, ts);
  });
}

app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*');
  ctx.set('Access-Control-Allow-Methods', 'OPTIONS, GET, PUT, POST, DELETE');
  if (ctx.url.indexOf('/getData') > -1) {
    const {
      request: {
        query: { value },
      },
    } = ctx;

    if (value === '1') {
      await sleep(10000);
      ctx.body = {
        data: value,
      };
    } else {
      await sleep(2000);
      ctx.body = {
        data: value,
      };
    }
    next();
  }
});

app.listen(3000, () => {
  console.log('listening on at port 3000');
});
